<?php
/**
 * 物资库存，入库，入库明细
 */
namespace App\Http\Controllers\Admin;
use App\Model\Stock;
use App\Model\MaterialList;
use App\Model\WarehouseMaterials;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class WarehouseMaterialsController extends Controller
{
    /**
     * 物资库存管理列表
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function warehouseMaterialslist(Request $quest)
    {
        $type = $quest->input("type",1);
        return view('admin/warehouseMaterials/warehouseMaterialslist')
            ->with('type',$type);
    }

    /**
     * 物资库存管理列表数据操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function warehouseMaterialslistdata(Request $request)
    {
        $query = $this->warehouseMaterialspub($request);
        $res=$query->paginate($request->get('limit',15))->toArray();
        $get_warehouse_type = WarehouseMaterials::get_warehouse_type();
        $data = [
            'code' => 0,
            'msg'   => '请求成功',
            'get_warehouse_type'   => $get_warehouse_type,
            'count' => $res['total'],
            'data'  => $res['data']
        ];
        return response()->json($data);
    }

    /**
     * 导出物资库存管理列表
     * @param $request
     * @return array
     */
    public function warehouseMaterialspub($request){
        $query= WarehouseMaterials::orderby('id','asc');
        if(isset($request['name']) && $name = $request['name']){  //物资名称
            $query->where('name','like','%'.$name.'%');
        }
        if(isset($request['goods_id']) && $goods_id = $request['goods_id']){ //分类名称
            $query->where('goods_id',$goods_id);
        }
        if(isset($request['checkcategory_id']) && $checkcategory_id = $request['checkcategory_id']){  //所属单位
            $query->where('checkcategory_id',$checkcategory_id);
        }
        return $query;
    }

    /**
     * 导出物资库存管理列表
     * @param Request $request
     * @return void
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function warehouseMaterialsexportone(Request $request)
    {
        $query = $this->warehouseMaterialspub($request);
        $dataExpor= $query->get()->toArray();

        $excel = new \PHPExcel();
        $excel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objActSheet = $excel->getActiveSheet();
        $letter = array('A','B','C','D','E','F','G','H','I');
        $title = [
            'A1'=>'序 号',
            'B1'=>'入库单号',
            'C1'=>'入库时间',
            'D1'=>'物资分类',
            'E1'=>'物资名称',
            'F1'=>'所属单位（人）',
            'G1'=>'入库数量',
            'H1'=>'入库类别',
            'I1'=>'提交人',
        ];
        foreach ($title as $tk=>$tv){
            $objActSheet->setCellValue($tk,$tv);
        }

        foreach ($letter as $l){
            $objActSheet->getStyle($l.'1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
        }

        /**填充内容*/
        $orirow = 2;
        $i = 1;

        foreach ($dataExpor as &$val) {
            $objActSheet->setCellValue("A".$orirow,$i);
            $objActSheet->setCellValue("B".$orirow,$val['checkcategory_id']??'');
            $objActSheet->setCellValue("C".$orirow,$val['company_id']??'');
            $objActSheet->setCellValue("D".$orirow,$val['goods_name']??'');
            $objActSheet->setCellValue("E".$orirow,$val['name']??'');
            $objActSheet->setCellValue("F".$orirow,$val['income_warehouse']??'');
            $objActSheet->setCellValue("G".$orirow,$val['warehouse']??'');
            $objActSheet->setCellValue("H".$orirow,$val['leave_warehouse']??'');
            $objActSheet->setCellValue("I".$orirow,$val['loss_warehouse']??'');
            $objActSheet->setCellValue("J".$orirow,$val['address']??'');
            $objActSheet->setCellValue("K".$orirow,$val['leader']??'');
            $objActSheet->setCellValue("L".$orirow,$val['leaderPhone']??'');

            $i ++;
            $orirow ++;

        }
        /**填充内容*/
        //统一设置填充内容左右居中、字号、宽度
        foreach ($letter as $l){
            for ($x = 2;$x<=$orirow;$x++){
                /*$objActSheet->getStyle($l.$x)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
                $objActSheet->getStyle($l.'2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中*/
                if($l=='A'){
                    $setHorizontal = \PHPExcel_Style_Alignment::HORIZONTAL_CENTER;
                }else{
                    $setHorizontal = \PHPExcel_Style_Alignment::HORIZONTAL_LEFT;
                }
                $objActSheet->getStyle($l.$x)->getAlignment()->setHorizontal($setHorizontal);
                $objActSheet->getStyle($l.$x)->getFont()->setSize(10);
                $objActSheet->getColumnDimension($l)->setWidth(20);

            }

        }
        /*$objActSheet->getColumnDimension('B')->setWidth(50);
        $objActSheet->getColumnDimension('C')->setWidth(50);
        $objActSheet->getColumnDimension('J')->setWidth(50);*/
        for ($x=1; $x<=($orirow); $x++) {
            $objActSheet->getRowDimension($x)->setRowHeight(30);//统一设置行高度

        }
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN,//细边框
                ),
            ),
        );
        $objActSheet->getStyle('A1:G1'.($orirow))->applyFromArray($styleArray);//设置粗边框


        $write = new \PHPExcel_Writer_Excel5($excel);
        ob_end_clean();
        //$date = Carbon::now()->toDateString();//表名前缀日期
        $date=time();
        $filename = '物资库存管理表-'.$date;
        $path = '/storage/excel/'.$filename.'.xls';
        $res = $write->save(public_path().$path);
        return response()->json(['code'=>0,'msg'=>'导出成功','url'=>'http://'.$_SERVER['HTTP_HOST'].$path,'file_name'=>$filename]);
    }

    /**
     * 物资库存管理数据处理
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function warehouseMaterialsRefer(Request $request)
    {
        $redata = $request->all();
        $id = isset($redata['id']) ? $redata['id'] : 0;
        $name = isset($redata['name']) ? $redata['name'] : '';
        $data = WarehouseMaterials::where('id',$id)->first();
        if ($request->isMethod('post')) {
            unset($redata['_token']);
            $name_data = WarehouseMaterials::where('name',$name)->first();
            if($data){
                if($name_data && $name_data['id']!=$id){
                    return redirect()->to(route('admin.stock.list'))->with(['status'=>'该名称已存在，请重新录入']);
                }
                $res = WarehouseMaterials::where('id', $id)->update($redata);
            }else{
                if($name_data){
                    return redirect()->to(route('admin.stock.list'))->with(['status'=>'该名称已存在，请重新录入']);
                }
                unset($redata['id']);
                $user = Auth::user();
                $userid = $user->id;
                $redata['user_id'] = $userid;
                $redata['created_at'] = date('Y-m-d H:i:s');
                $res = WarehouseMaterials::insertGetId($redata);
            }
            return redirect()->to(route('admin.stock.list'))->with(['status'=>'提交成功']);
        }
    }

    /**
     * 物资库存管理数据删除
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function warehouseMaterialsDelete(Request $request)
    {
        $redata = $request->all();
        $id = isset($redata['id']) ? $redata['id'] : 0;
        $data = Stock::where('id',$id)->first();
        $materialList_data = MaterialList::where('goods_id',$id)->first();
        if($materialList_data){
            return redirect()->to(route('admin.stock.list'))->with(['status'=>'该分类已被使用，不能删除']);
        }
        $resu = Stock::where('id', $id)->delete();
        return redirect()->to(route('admin.stock.list'))->with(['status'=>'提交成功']);
    }

    /**
     * 物资库存管理列表
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function stocklist(Request $quest)
    {
        $type = $quest->input("type",1);
        return view('admin/stock/stocklist')
            ->with('type',$type);
    }

    /**
     * 物资库存管理列表数据操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function stocklistdata(Request $request)
    {
        $query = $this->stockpub($request);
        $res=$query->paginate($request->get('limit',15))->toArray();
        $data = [
            'code' => 0,
            'msg'   => '请求成功',
            'count' => $res['total'],
            'data'  => $res['data']
        ];
        return response()->json($data);
    }

    /**
     * 导出物资库存管理列表
     * @param $request
     * @return array
     */
    public function stockpub($request){
        $query= Stock::orderby('id','asc');
        if(isset($request['name']) && $name = $request['name']){  //物资名称
            $query->where('name','like','%'.$name.'%');
        }
        if(isset($request['goods_id']) && $goods_id = $request['goods_id']){ //分类名称
            $query->where('goods_id',$goods_id);
        }
        if(isset($request['checkcategory_id']) && $checkcategory_id = $request['checkcategory_id']){  //所属单位
            $query->where('checkcategory_id',$checkcategory_id);
        }
        return $query;
    }

    /**
     * 导出物资库存管理列表
     * @param Request $request
     * @return void
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function stockexportone(Request $request)
    {
        $query = $this->stockpub($request);
        $dataExpor= $query->get()->toArray();

        $excel = new \PHPExcel();
        $excel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objActSheet = $excel->getActiveSheet();
        $letter = array('A','B','C','D','E','F','G');
        $title = [
            'A1'=>'序 号',
            'B1'=>'所属单位（人）',
            'C1'=>'单位（个人）名称',
            'D1'=>'物资分类',
            'E1'=>'物资名称',
            'F1'=>'入库数量',
            'G1'=>'库存数量',
            'H1'=>'出库数量',
            'I1'=>'损耗数量',
            'J1'=>'具体位置',
            'K1'=>'联系人',
            'L1'=>'联系电话',
        ];
        foreach ($title as $tk=>$tv){
            $objActSheet->setCellValue($tk,$tv);
        }

        foreach ($letter as $l){
            $objActSheet->getStyle($l.'1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
        }

        /**填充内容*/
        $orirow = 2;
        $i = 1;

        foreach ($dataExpor as &$val) {
            $objActSheet->setCellValue("A".$orirow,$i);
            $objActSheet->setCellValue("B".$orirow,$val['checkcategory_id']??'');
            $objActSheet->setCellValue("C".$orirow,$val['company_id']??'');
            $objActSheet->setCellValue("D".$orirow,$val['goods_name']??'');
            $objActSheet->setCellValue("E".$orirow,$val['name']??'');
            $objActSheet->setCellValue("F".$orirow,$val['income_warehouse']??'');
            $objActSheet->setCellValue("G".$orirow,$val['warehouse']??'');
            $objActSheet->setCellValue("H".$orirow,$val['leave_warehouse']??'');
            $objActSheet->setCellValue("I".$orirow,$val['loss_warehouse']??'');
            $objActSheet->setCellValue("J".$orirow,$val['address']??'');
            $objActSheet->setCellValue("K".$orirow,$val['leader']??'');
            $objActSheet->setCellValue("L".$orirow,$val['leaderPhone']??'');

            $i ++;
            $orirow ++;

        }
        /**填充内容*/
        //统一设置填充内容左右居中、字号、宽度
        foreach ($letter as $l){
            for ($x = 2;$x<=$orirow;$x++){
                /*$objActSheet->getStyle($l.$x)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
                $objActSheet->getStyle($l.'2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中*/
                if($l=='A'){
                    $setHorizontal = \PHPExcel_Style_Alignment::HORIZONTAL_CENTER;
                }else{
                    $setHorizontal = \PHPExcel_Style_Alignment::HORIZONTAL_LEFT;
                }
                $objActSheet->getStyle($l.$x)->getAlignment()->setHorizontal($setHorizontal);
                $objActSheet->getStyle($l.$x)->getFont()->setSize(10);
                $objActSheet->getColumnDimension($l)->setWidth(20);

            }

        }
        /*$objActSheet->getColumnDimension('B')->setWidth(50);
        $objActSheet->getColumnDimension('C')->setWidth(50);
        $objActSheet->getColumnDimension('J')->setWidth(50);*/
        for ($x=1; $x<=($orirow); $x++) {
            $objActSheet->getRowDimension($x)->setRowHeight(30);//统一设置行高度

        }
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN,//细边框
                ),
            ),
        );
        $objActSheet->getStyle('A1:G1'.($orirow))->applyFromArray($styleArray);//设置粗边框


        $write = new \PHPExcel_Writer_Excel5($excel);
        ob_end_clean();
        //$date = Carbon::now()->toDateString();//表名前缀日期
        $date=time();
        $filename = '物资库存管理表-'.$date;
        $path = '/storage/excel/'.$filename.'.xls';
        $res = $write->save(public_path().$path);
        return response()->json(['code'=>0,'msg'=>'导出成功','url'=>'http://'.$_SERVER['HTTP_HOST'].$path,'file_name'=>$filename]);
    }



}
